package asteroids.model.programs.parsing.statements;

import java.util.List;
import java.util.Map;

import be.kuleuven.cs.som.annotate.Basic;

import asteroids.model.Ship;
import asteroids.model.programs.parsing.expressions.Expression;
import asteroids.model.programs.parsing.types.*;

/**
 * A class of if statements.
 * An if statement executes a statement if an expression is true, else it executes another statement.
 * 
 * @author Thijs Dieltjens - Wim Konings
 * @version 2.0
 */
public class IfStatement extends Statement {

	public IfStatement(Expression e, Statement ifStatement, Statement elseStatement,int line, int column){
		super(line,column);
		this.condition = e;
		this.ifStatement=ifStatement;
		this.elseStatement=elseStatement;
	}

	@Basic
	public Expression getCondition() {
		return condition;
	}

	private Expression condition;

	@Basic
	public Statement getIfStatement() {
		return ifStatement;
	}

	private Statement ifStatement;

	@Basic
	public Statement getElseStatement() {
		return elseStatement;
	}

	private Statement elseStatement;

	public Statement getResultStatement(Ship ship){
		if(getCondition().eval(ship, null) instanceof BooleanLiteral && ((BooleanLiteral) getCondition().eval(ship, null)).getValue()==true){
			return getIfStatement();
		}
		else{
			return getElseStatement();
		}
	}

	@Override
	public void execute(Ship ship) {
		if( getCondition().eval(ship, null) instanceof BooleanLiteral && ((BooleanLiteral) getCondition().eval(ship, null)).getValue()==true){
			getIfStatement().execute(ship);
		}
		else{
			getElseStatement().execute(ship);
		}
	}

	@Override
	public List<String> getTypeCheckErrors(List<String> errors, Map<String, Type> globals) {
		errors = getCondition().getTypeCheckErrors(errors, globals);
		try{
			if(getCondition().eval(null, globals).getClass() != BooleanLiteral.class){
				errors.add(getLine()+"-"+getColumn()+": Invalid if-expression.");
			}
		}
		catch(NullPointerException e){
			errors.add(getLine()+"-"+ getColumn()+" : Invalid if-expression");
		}
		errors = (getIfStatement().getTypeCheckErrors(errors, globals));
		errors =(getElseStatement().getTypeCheckErrors(errors, globals));
		errors = getCondition().getTypeCheckErrors(errors, globals);
		return errors;
	}

	@Override
	public boolean containsActionStatement() {
		if(getIfStatement().containsActionStatement() || getElseStatement().containsActionStatement()){
			return true;
		}
		return false;
	}

}
